package com.pingbu.common.utils;

import com.pingbu.tijian.hospital.backapi.config.GlobalSet;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.mozilla.universalchardet.UniversalDetector;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

public class PbFileUtils {


    public static String getFileExtension(String fileName){
        if ((fileName == null) || (fileName.lastIndexOf(".") == -1) || (fileName.lastIndexOf(".") == fileName.length() - 1)) {
            return null;
        }
        return StringUtils.lowerCase(fileName.substring(fileName.lastIndexOf(".") + 1));
    }

    /**
     * 获得文件编码
     * @param fileName
     * @return
     * @throws Exception
     */
    public static String codeString(String fileName) throws Exception {
        String charset = "";
        byte[] bs = new byte[10240];
        FileInputStream is = null;
        try {
            is = new FileInputStream(fileName);
            int len=is.read(bs,0,10240);

            UniversalDetector detector = new UniversalDetector(null);
            detector.handleData(bs, 0, len);
            detector.dataEnd();

            charset = detector.getDetectedCharset();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(is!=null){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return charset;
    }



    /**
     * 删除解压之后的文件
     * @param file
     */
    public static void delUnFiles(File file){
        File[] files = file.listFiles();
        if(files != null){
            for (File f1 : files) {
                f1.delete();
                if (f1.isDirectory()) {
                    delUnFiles(f1);
                    f1.delete();
                }
            }
        }
    }

    public static  Map<String, String> getFilePath(String filePath, MultipartFile uploadFile1) {
        Map<String, String> maps = new HashMap<>();
        String fileDatePath = createFileDatePath();
        String randomPath = PbFileUtils.randomFileName(uploadFile1.getOriginalFilename());
        String fullPath = filePath+"/"+fileDatePath+ randomPath;
        String relPath = fileDatePath+ randomPath;
        maps.put("fullPath", fullPath);
        maps.put("realPath", relPath);
        return maps;
    }

    public static String createFileDatePath(){
        Date date = new Date();
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM");
        String dateStr1 = sdf1.format(date);
        SimpleDateFormat sdf2 = new SimpleDateFormat("dd");
        String dateStr2 = sdf2.format(date);
        String fileDatePath = dateStr1+"/"+dateStr2+"/";
        return  fileDatePath;
    }

    public static String getFileNameWithoutExtension(String fileName) {
        if ((fileName == null) || (fileName.lastIndexOf(".") == -1)) {
            return null;
        }
        return fileName.substring(0, fileName.lastIndexOf("."));
    }

    public static String randomFileName(String fileName){
        String ext = getFileExtension(fileName);
        String rnd = PbTimeUtils.formatTime(new Date(),"yyyyMMddHHmmss")+ RandomStringUtils.randomAlphanumeric(6);
        String res = rnd ;
        if(StringUtils.isNotEmpty(ext)){
            res+="."+ext;
        }
        return res;
    }

    /**
     * 删除文件
     * @param fileFullPath
     */
    public static void delFile(String fileFullPath){

        File f1=new File(fileFullPath);
        if(f1.exists()){
            f1.delete();
        }

    }

    public static Boolean saveFile(String fileFullPath, InputStream fis){
        OutputStream os = null;
        try {
            // 2、保存到临时文件
            // 1K的数据缓冲
            byte[] bs = new byte[1024];
            // 读取到的数据长度
            int len;
            // 输出的文件流保存到本地文件

            File saveFile = new File(fileFullPath);
            File saveDir = saveFile.getParentFile();
            if(!saveDir.exists()){
                saveDir.mkdirs();
            }
            os = new FileOutputStream(saveFile);
            // 开始读取
            while ((len = fis.read(bs)) != -1) {
                os.write(bs, 0, len);
            }

        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 完毕，关闭所有链接
            try {
                os.close();
                fis.close();

                return true;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return false;
    }

    public static String getBase64FromInputStream(InputStream in) {
        // 将图片文件转化为字节数组字符串，并对其进行Base64编码处理
        byte[] data = null;
        // 读取图片字节数组
        try {
            ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
            byte[] buff = new byte[10240];
            int rc = 0;
            while ((rc = in.read(buff, 0, 10240)) > 0) {
                swapStream.write(buff, 0, rc);
            }
            data = swapStream.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return new String(Base64.encodeBase64(data));
    }



}
